<?php
namespace App\Service\ApiXcx;

use App\Service\Admin\ImageService;
use Illuminate\Support\Facades\DB;

class UserService extends BaseService
{
    //用户

    protected $app_id = 'wx081bb28635ee4455';//'wxbf3d9e70e4eb9fb0';
    protected $app_secret = 'f0a1e29245c9186cddd4f155302a6707';//'65df5b844267bf0c8624758557b8ccc7';

    /**
     * 保存用户信息
     * @param array $pas
     * @return array
     */
    public function wxByOpenid($pas)
    {
        $wxOne = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('openid', $pas['openid'])
            ->first();
        if (empty($wxOne)) {
            $nick = $pas['nickname'] ? $pas['nickname'] : time().rand(10000, 99999);
            $token = toToken();
            $uData = [
                'openid' => $pas['openid'],
                'parent_id' => $pas['parent_id'],
                'nickname' => $nick,
                'avatarUrl' => $pas['avatarUrl'],
                'serial' => toUserno(),
                'token' => $token,
                'wxjson' => json_encode($pas, JSON_UNESCAPED_UNICODE),
                'addtime' => toDate(),
                'lasttime' => toDate(),
            ];
            $this->dbConn($this->dbUser)->insertGetId($uData);
            $this->dbConn($this->dbUlogin)->insertGetId([
                'token' => $token, 'addtime' => toDate(),
            ]);
        } else {
            $uData = [
                'wxjson' => json_encode($pas, JSON_UNESCAPED_UNICODE),
                'lasttime' => toDate(),
            ];
            if($wxOne['parent_id'] == 0) {
                $uData['parent_id'] = $pas['parent_id'];
            }
            if (!$wxOne['serial']) $uData['serial'] = toUserno();
            DB::table($this->dbUser)->where('id', $wxOne['id'])->update($uData);
            $token = $wxOne['token'];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $token);
    }

    /**
     * 上传头像
     * @param int $uid
     * @param array $imgs【imglink，w，h】
     */
    public function setHead($uid, $imgs)
    {
        $imglink = $imgs['link'];
        (new ImageService())->addOne($imglink, $imgs['w'], $imgs['h']);
        $uOne = (array) DB::table($this->dbUser)->where('id', $uid)->first();
        if (empty($uOne)) {
            return array('code' => -2, 'msg' => '该用户不存在');
        }
        $uData = [
            'avatarUrl' => $imglink,
            'uptime' => toDate(),
        ];
        $res = DB::table($this->dbUser)->where('id', $uid)->update($uData);
        if (!$res) {
            return array('code' => -1, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 上传推广二维码
     * @param int $uid
     * @param array $imgs【imglink，w，h】
     */
    public function setQR($uid, $imgs)
    {
        $imglink = $imgs['link'];
        (new ImageService())->addOne($imglink, $imgs['w'], $imgs['h']);
        $uOne = (array) DB::table($this->dbUser)->where('id', $uid)->first();
        if (empty($uOne)) {
            return array('code' => -2, 'msg' => '该用户不存在');
        }
        $uData = [
            'qr_image' => $imglink,
            'uptime' => toDate(),
        ];
        $res = DB::table($this->dbUser)->where('id', $uid)->update($uData);
        if (!$res) {
            return array('code' => -1, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 上传推广海报
     * @param int $uid
     * @param array $imgs【imglink，w，h】
     */
    public function setPoster($uid, $imgs)
    {
        $imglink = $imgs['link'];
        (new ImageService())->addOne($imglink, $imgs['w'], $imgs['h']);
        $uOne = (array) DB::table($this->dbUser)->where('id', $uid)->first();
        if (empty($uOne)) {
            return array('code' => -2, 'msg' => '该用户不存在');
        }
        $uData = [
            'poster' => $imglink,
            'uptime' => toDate(),
        ];
        $res = DB::table($this->dbUser)->where('id', $uid)->update($uData);
        if (!$res) {
            return array('code' => -1, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 海报合成
     * @param int $uid
     * @param array $imgs【imglink，w，h】
     */
    public function conflatePoster($user_info)
    {
        if($user_info['poster']){
            return array('code' => 0, 'msg' => 'success', 'data' => $user_info['poster']);
        }
        $qrCodePath = $user_info['qr_image'];
        $compressedQrCodePath = '';
        if (empty($qrCodePath)) {
            // 生成微信小程序二维码
            $appId = $this->app_id; // 替换为您的小程序AppID
            $appSecret = $this->app_secret; // 替换为您的小程序AppSecret
            $page = 'pages/index/index'; // 小程序页面路径
            $scene = 'user_id=' . $user_info['id']; // 传递的参数

            // 获取access_token
            $accessToken = $this->getAccessToken($appId, $appSecret);
            if (!$accessToken) {
                return array('code' => -1, 'msg' => '获取access_token失败');
            }

            // 生成小程序二维码
            $qrCodeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
            $postData = json_encode([
                'scene' => $scene,
                'page' => $page,
                'width' => 100,
            ]);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $qrCodeUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
            ]);
            $qrCodeImage = curl_exec($ch);
            curl_close($ch);
            // 保存二维码
            $qrCodePath = 'upload/qrcodes/user_' . $user_info['id'] . '.png';
            file_put_contents($qrCodePath, $qrCodeImage);

            // 创建图像资源并压缩二维码到 100x100
            $qrCodeImageResource = imagecreatefromstring($qrCodeImage); // 从字符串创建图像资源
            $scaledImage = imagecreatetruecolor(100, 100); // 创建 100x100 的新图像

            // 将二维码缩放到 100x100
            imagecopyresampled($scaledImage, $qrCodeImageResource, 0, 0, 0, 0, 100, 100, imagesx($qrCodeImageResource), imagesy($qrCodeImageResource));

            // 保存压缩后的二维码
            $compressedQrCodePath = 'upload/qrcodes/compressed_user_' . $user_info['id'] . '.png';
            imagepng($scaledImage, $compressedQrCodePath); // 保存压缩后的二维码

            // 释放内存
            imagedestroy($qrCodeImageResource);
            imagedestroy($scaledImage);
            $uData = [
                'qr_image' => $compressedQrCodePath,
                'uptime' => toDate(),
            ];
            DB::table($this->dbUser)->where('id', $user_info['id'])->update($uData);
        }

        $bg = 'images/posterbg2.png';

        // Check if background image exists
        if (!file_exists($bg)) {
            return array('code' => -1, 'msg' => '背景图片不存在');
        }
        if (!$compressedQrCodePath) {
            return $this->toback(-2, '没有码图');
        }

        // Create image resources
        $background = imagecreatefrompng($bg);
        $qr_code = imagecreatefromstring(file_get_contents($compressedQrCodePath));

        // Get image dimensions
        $bg_width = imagesx($background);
        $bg_height = imagesy($background);
        $qr_width = imagesx($qr_code);
        $qr_height = imagesy($qr_code);

        // Calculate position to place QR code (bottom right corner with 20px margin)
        $qr_x = $bg_width - $qr_width - 135;
//        $qr_y = $bg_height - $qr_height - 85;
        $qr_y = $bg_height - $qr_height - 100;

        // Merge images
        imagecopy($background, $qr_code, $qr_x, $qr_y, 0, 0, $qr_width, $qr_height);

        $timestamp = time();
        $uploadDir = 'upload/' . date('Ymd', $timestamp);
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true); // Create directory if it doesn't exist
        }

        // Save the merged image in the new directory
        $output_file = $uploadDir . '/merged_poster' . $user_info['id'] .'_' . $timestamp . '.png';
        imagepng($background, $output_file);

        // Free up memory
        imagedestroy($background);
        imagedestroy($qr_code);

        return array('code' => 0, 'msg' => 'success', 'data' => $output_file);
    }

    /**
     * 获取access_token
     * @param string $appId
     * @param string $appSecret
     * @return string|null
     */
    private function getAccessToken($appId, $appSecret)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
        $response = file_get_contents($url);
        $data = json_decode($response, true);
        return isset($data['access_token']) ? $data['access_token'] : null;
    }

    /**
     * 上传头像
     * @param int $uid
     * @param string $nick
     */
    public function setNick($uid, $nick)
    {
        $uOne = (array) DB::table($this->dbUser)->where('id', $uid)->first();
        if (empty($uOne)) {
            return array('code' => -2, 'msg' => '该用户不存在');
        }
        $uData = [
            'nickname' => $nick,
            'uptime' => toDate(),
        ];
        $res = DB::table($this->dbUser)->where('id', $uid)->update($uData);
        if (!$res) {
            return array('code' => -1, 'msg' => 'error');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 领取优惠劵
     * @param int $uid
     */
    public function addCouponByNew($uid)
    {
        $total = DB::table($this->dbUcoupon)
            ->where('type', 1)
            ->where('uid', $uid)
            ->count();
        if ($total) {
            return array('code' => -2, 'msg' => '该用户已领取');
        }
        $tmpOnes = DB::table($this->dbUcouponTmp)
            ->where('del', 0)
            ->where('type', 1)
            ->get();
        if (!count($tmpOnes)) {
            return array('code' => -2, 'msg' => '新用户优惠劵未设置');
        }
        $arys = [];
        foreach ($tmpOnes as $v) {
            $v = (array) $v;
            //有效期
            $expire = time() + $v['expire'] * 3600 * 24;
            $expire = date('Y-m-d H:i:s', $expire);
            $arys[] = [
                'uid' => $uid,
                'quata' => $v['quata'],
                'scene' => $v['scene'],
                'full' => $v['full'],
                'reduce' => $v['reduce'],
                'expire' => $expire,
                'addtime' => toDate(),
            ];
        }
        if (!count($arys)) {
            return array('code' => -2, 'msg' => '新用户优惠劵失败');
        }
        DB::beginTransaction(); //开启事务
        try {
            foreach ($arys as $v) {
                $lastid = DB::table($this->dbUcoupon)->insertGetId($v);
                if (!$lastid) {
                    return array('code' => -2, 'msg' => '领取失败');
                }
            }
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success');
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code'=>-1, 'msg'=>'操作失败');
        }
    }

    //等级列表
    public function getLevelList()
    {
        $res = DB::table($this->dbUlevel)
            ->where('del', 0)
            ->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => [], 'total' => 0);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $icon = file_exists($v['icon']) ? env('DOMAIN').'/'.$v['icon'] : '';
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'ver' => $v['ver'],
                'describe' => $v['describe'],
                'icon' => $icon,
                'price' => $v['price'] / 100,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => count($arys));
    }

    //充值记录列表
    public function getRechargeList($pages, $uid)
    {
        $start = ($pages['page'] - 1) * $pages['size'];
        $db = $this->dbConn($this->dbPay, ['type' => 1, 'status' => 2, 'uid' => $uid]);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['size'])
            ->select('addtime', 'money', 'balance')
            ->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => 'success', 'data' => [], 'total' => $total);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'title' => '充值成功',
                'addtime' => $v['addtime'],
                'money' => number_format($v['money'] / 100, 2),
                'balance' => number_format($v['balance'] / 100, 2),
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    //获取用户信息
    public function getOneByToken($token)
    {
        $this->signBreak($token); //断签处理
        $tx = $this->teamIncomeReset($token); //体现统计计算
        $res = (array) DB::table($this->dbUser)
            ->where('del', 0)
            ->where('token', $token)
            ->orderBy('id', 'desc')
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '用户不存在，或已在其他设备上登录');
        }
        if ($res['phone']) {
            $lastUser = (array) $this->dbConn($this->dbUlogin)
                ->where('phone', $res['phone'])
                ->orderBy('id', 'desc')
                ->first();
            if ($lastUser && $lastUser['token'] != $token) {
                return array('code' => -2, 'msg' => '当前账号登录已失效，或已在其他设备上登录');
            }
        }
        if (!$res['serial']) {
            $serial = $res['serial'] = toUserno();
            DB::table($this->dbUser)->where('id', $res['id'])->update(['serial' => $serial]);
        }
        $res['balance'] = $res['balance'] / 100;
        if (substr($res['avatarUrl'], 0, 4) != 'http') {
            $res['avatarUrl'] = $res['avatarUrl'] ? env('DOMAIN') . '/' . $res['avatarUrl'] : '';
        }
        $res['version'] = 'V1.0';
        //会员等级
        $level_id = $res['level_id'] ? $res['level_id'] : 0;
        $levelSelOne = (array) DB::table($this->dbUlevel)
            ->where('del', 0)
            ->where('id', $level_id)
            ->first();
        $levelNextOne = (array) DB::table($this->dbUlevel)
            ->where('del', 0)
            ->where('id', '>', $level_id)
            ->orderBy('id', 'asc')
            ->first();
//        $res['levelSelName'] = empty($levelSelOne) ? '普通会员' : $levelSelOne['title'];
//        $res['ver'] = empty($levelSelOne) ? '-' : $levelSelOne['ver'];
//        $res['levelNextName'] = empty($levelNextOne) ? '普通会员' : $levelNextOne['title'];
        $res['levelSelName'] = '普通会员';
        $res['levelNextName'] = empty($levelNextOne) ? '' : $levelNextOne['title'];
        if ($res['is_auto'] == 3) {
            $res['levelSelName'] = 'SVIP会员';
            $res['levelNextName'] = '';
            $res['level_id'] = 12;
        } else if (in_array($res['is_auto'], [1, 2])) {
            if (!empty($levelSelOne)) {
                $res['levelSelName'] = $levelSelOne['title'];
            }
        }
        $res['levelSelFlag'] = 1; //V级别1
        $res['levelNextFlag'] = 2; //V级别2
        //优惠劵
        $res['couponNum'] = DB::table($this->dbUcoupon)
            ->where('uid', $res['id'])
            ->where('status', 2)
            ->count();
        //待付款的
        //$orderDB = DB::table($this->dbOrder)->where('iscancel', 1)->where('uid', $res['id']);
        $res['orderPayNum'] = DB::table($this->dbOrder)
            ->where('iscancel', 1)
            ->where('uid', $res['id'])
            ->where('status', 1)
            ->count();
        $res['orderSendNum'] = DB::table($this->dbOrder)
            ->where('iscancel', 1)
            ->where('uid', $res['id'])
            ->where('delivery', 1)
            ->where('status', 2)
            ->count();
        $res['orderAcceptNum'] = DB::table($this->dbOrder)
            ->where([
                ['iscancel', '=', 1],
                ['uid', '=', $res['id']],
                ['delivery', '=', 1],
                ['status', '=', 3],
            ])
            ->orWhere([
                ['iscancel', '=', 1],
                ['uid', '=', $res['id']],
                ['delivery', '=', 2],
                ['status', '=', 2],
            ])
            ->count();
        $res['orderCancelNum'] = DB::table($this->dbOrder)
            ->where('uid', $res['id'])
            //->where('iscancel', '>', 1)
            ->where('iscancel', 2)
            ->count();
        //体现计算
        $res['all_income'] = toNumber($res['all_income']);
        $res['income'] = toNumber($res['income']);
        $res['settle_income'] = toNumber($res['settle_income']);
        $res['income_freeze'] = toNumber($res['income_freeze']);
        $tixian = $res['all_income'] - $res['income'] - $res['settle_income'] - $res['income_freeze'];
        $res['tixian'] = toNumber($tixian * 100);
        //用户标签
        $tagOnes = $this->dbConn($this->dbUtag)
            ->where('del', 0)
            ->where('uid', $res['id'])
            ->get();
        $res['tagList'] = [];
        if (count($tagOnes)) {
            foreach ($tagOnes as $v) {
                $res['tagList'][] = [
                    'id' => $v->id,
                    'title' => $v->title,
                ];
            }
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $res);
    }

    //断签处理
    public function signBreak($token)
    {
        $uOne = (array) $this->dbConn($this->dbUser)->where('token', $token)->first();
        if (empty($uOne)) { return; }
        $yesday = toYesterday();
        if ($uOne['last_sign_time'] >= $yesday['start']) {
            return;
        }
        $this->dbConn($this->dbUser)->where('token', $token)
            ->update(['continuous_sign_day' => 0]);
        return;
    }

//    //获取团队列表
//    public function getTeamList($pages, $uid)
//    {
//        $start = ($pages['start'] - 1) * $pages['limit'];
//        $db = DB::table($this->dbUser)->where('parent_id', $uid);
//        $total = $db->count();
//        $res = $db->skip($start)->take($pages['limit'])
//            ->orderBy('id', 'desc')
//            ->get()
//            ->map(function ($value){
//                return (array)$value;
//            })
//            ->toArray();
//        return array('code' => 0, 'msg' => 'success', 'data' => $res, 'total' => $total);
//    }

    //获取团队列表
    public function getTeamList($pages, $uid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('parent_id', $uid);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get()->map(function ($value){
                        return (array)$value;
                    })
            ->toArray();
        if (!count($res)) {
            return $this->toback(0, '', [], 0);
        }
        foreach ($res as $k => $v) {
            $head = '';
            if (substr($v['avatarUrl'], 0, 4) == 'http') {
                $head = $v['avatarUrl'];
            } else if (file_exists($v['avatarUrl'])) {
                $head = env('DOMAIN') . '/' . $v['avatarUrl'];
            }
            $res[$k]['avatarUrl'] = $head;
            $res[$k]['phone'] = $v['phone'] ? $v['phone'] : '-';
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $res, 'total' => $total);
    }

    //获取团队订单列表
    public function getTeamOrderList($pages, $uid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbOrder . ' as o')
            ->leftJoin($this->dbUser . ' as u', 'u.id', '=', 'o.uid')
            ->where('u.parent_id', $uid);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->select('o.id', 'o.orderno', 'u.phone', 'u.avatarUrl', 'o.uname', 'o.price', 'o.addtime')
            ->orderBy('id', 'desc')
            ->get();
//            ->map(function ($value){
//                return (array)$value;
//            })
//            ->toArray();
        $arys = [];
        if (count($res)) {
            foreach ($res as $k => $v) {
                $v = (array) $v;
                $v['price'] = toNumber($v['price']);
                $v['avatarUrl'] = substr($v['avatarUrl'], 0, 4)=='http'
                    ? $v['avatarUrl'] : env('DOMAIN').'/'.$v['avatarUrl'];
                $commission = 0;
                $oskuOnes = $this->dbConn($this->dbOsku)->where('order_id', $v['id'])->get();
                if (count($oskuOnes)) {
                    foreach ($oskuOnes as $vv) {
                        $vv = (array) $vv;
                        $skuOne = (array) $this->dbConn($this->dbGsku)
                            ->where('id', $vv['sku_id'])->first();
                        $rate = !empty($skuOne)&&$skuOne['commission_rate']<100 ? $skuOne['commission_rate'] / 100 : 1;
                        $price = !empty($skuOne)&&$skuOne['price'] ? $skuOne['price'] : 0;
                        $commission += $price * $vv['num'] * $rate;
                    }
                }
                $v['commission'] = toNumber($commission);
                $arys[] = $v;
            }
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

//    //签到
//    public function sign($user)
//    {
//        $yesterday = toYesterday();
//        $today = toToday();
//        $last_sign_time = $user['last_sign_time'];
//        if ($last_sign_time > $today['start']) {
//            return array('code' => -2, 'msg' => '您今天已签到');
//        }
//        //$config = getConfig();
//        $config = $this->getConfig();
//        if ($config['code'] < 0) {
//            return $this->toback(-2, $config['msg']);
//        }
//        $config = $config['data'];
//        if ($last_sign_time >= $yesterday['start']) {
//            $continuous_sign_day = ++$user['continuous_sign_day'];
//            if($continuous_sign_day == 2){
//                $points = $config['sign_point'] + $config['continuous_sign_two_point'];
//            }elseif ($continuous_sign_day == 4) {
//                $points = $config['sign_point'] + $config['continuous_sign_four_point'];
//            }else {
//                $points = $config['sign_point'];
//            }
//            $after_points = $user['points'] + $points;
//            $user_data = [
//                'points' => $after_points,
//                'continuous_sign_day' => $continuous_sign_day,
//                'last_sign_time' => toDate()
//            ];
//            $point_log = [
//                'uid' => $user['id'],
//                'type' => 1,
//                'before_points' => $user['points'],
//                'change_points' => $points,
//                'after_points' => $after_points,
//                'reason' => '签到送积分',
//                'relation_value' => $continuous_sign_day,
//                'addtime' => toDate()
//            ];
//        }else{
//            $after_points = $user['points'] + $config['sign_point'];
//            $user_data = [
//                'points' => $after_points,
//                'continuous_sign_day' => 1,
//                'last_sign_time' => toDate()
//            ];
//            $point_log = [
//                'uid' => $user['id'],
//                'type' => 1,
//                'before_points' => $user['points'],
//                'change_points' => $config['sign_point'],
//                'after_points' => $after_points,
//                'reason' => '签到送积分',
//                'relation_value' => 1,
//                'addtime' => toDate()
//            ];
//        }
//
//        DB::beginTransaction(); //开启事务
//        try {
//            DB::table($this->dbUser)->where('id', $user['id'])->update($user_data);
//            DB::table($this->dbUserPointLog)->insertGetId($point_log);
//            DB::commit(); //提交事务
//            return array('code'=>0, 'msg'=>'success');
//        } catch (\Exception $e) {
//            DB::rollBack(); //事务回滚
//            echo $e->getMessage();
//            return array('code'=>-1, 'msg'=>'操作失败');
//        }
//    }

    //签到
    public function sign($user)
    {
        $yesterday = toYesterday()['start']; //昨天开始时间
        $today = toToday();
        $last_sign_time = $user['last_sign_time'];
        if ($last_sign_time > $today['start']) {
            return array('code' => -2, 'msg' => '您今天已签到');
        }
        $config = $this->getConfig();
        if ($config['code'] < 0) {
            return $this->toback(-2, $config['msg']);
        }
        $config = $config['data'];
        $continuous_sign_day = $user['continuous_sign_day']; //连续签到天数
        if ($last_sign_time >= $yesterday) { //连续
            if ($continuous_sign_day == 3) {
                $points = $config['sign_point'] + $config['continuous_sign_4_point'];
            } else if ($continuous_sign_day == 6) {
                $points = $config['sign_point'] + $config['continuous_sign_7_point'];
            } else {
                $points = $config['sign_point'];
            }
            $after_points = $user['points'] + $points;
            $continuous_sign_day = $continuous_sign_day + 1;
            $user_data = [
                'points' => $after_points,
                'continuous_sign_day' => $continuous_sign_day,
                'last_sign_time' => toDate()
            ];
        } else { //断签
            $points = $config['sign_point'];
            $after_points = $user['points'] + $config['sign_point'];
            $continuous_sign_day = 1;
            $user_data = [
                'points' => $after_points,
                'continuous_sign_day' => $continuous_sign_day,
                'last_sign_time' => toDate()
            ];
        }
        $point_log = [
            'uid' => $user['id'],
            'type' => 1,
            'before_points' => $user['points'],
            'change_points' => $points,
            'after_points' => $after_points,
            'reason' => '签到送积分',
            'relation_value' => $continuous_sign_day,
            'addtime' => toDate()
        ];
        DB::beginTransaction(); //开启事务
        try {
            DB::table($this->dbUser)->where('id', $user['id'])->update($user_data);
            DB::table($this->dbUserPointLog)->insertGetId($point_log);
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success');
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code'=>-1, 'msg'=>'操作失败');
        }
    }

    //积分明细
    public function getPointsLog($pages, $uid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbUserPointLog)->where('uid', $uid);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get()
            ->map(function ($value){
                return (array)$value;
            })
            ->toArray();
        return array('code' => 0, 'msg' => 'success', 'data' => $res, 'total' => $total);
    }

    //修改手机号
    public function setPhone($token, $phone)
    {
        $res = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('phone', $phone)
            ->where('token', '<>', $token)
            ->first();
        if (!empty($res)) {
            return $this->toback(-2, '该手机号已被使用');
        }
        $res = (array) $this->dbConn($this->dbUser)
            ->where('token', $token)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $tokenNew = toToken();
        $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('token', $token)
            ->update(['phone' => $phone, 'token' => $tokenNew]);
        $this->dbConn($this->dbUlogin)->insertGetId([
            'phone' => $phone, 'token' => $tokenNew, 'addtime' => toDate(),
        ]);
        return $this->toback(0, '', $tokenNew);
    }

    //重新计算团长收益
    public function teamIncomeReset($token)
    {
        $arys = [
            'all_income' => 0, //总收益
            'income' => 0, //已提现的
            'settle_income' => 0, //提现审核中的
            'income_freeze' => 0, //未收货待结算的
            'tixian' => 0, //可提现的
        ];
        $res = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('token', $token)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $uid = $res['id'];
//        $uOnes = $this->dbConn($this->dbUser)
//            ->where('del', 0)
//            ->where('parent_id', $uid)
//            ->get();
//        if (!count($uOnes)) {
//            return $this->toback(-2, '没有成员');
//        }
//        $subUids = [];
//        foreach ($uOnes as $v) {
//            $subUids[] = $v->id;
//        }
//        //所有的
//        $orderAlls = $this->dbConn($this->dbOrder)
//            ->where('del', 0)
//            ->whereIn('uid', $subUids)
//            ->get();
//        if (count($orderAlls)) {
//            foreach ($orderAlls as $v) {
//                $oskuOnes = $this->dbConn($this->dbOsku)->where('order_id', $v->id)->get();
//                if (count($oskuOnes)) {
//                    foreach ($oskuOnes as $vv) {
//                        $vv = (array) $vv;
//                        $skuOne = (array) $this->dbConn($this->dbGsku)
//                            ->where('id', $vv['sku_id'])->first();
//                        $rate = !empty($skuOne)&&$skuOne['commission_rate']<100 ? $skuOne['commission_rate'] / 100 : 1;
//                        $price = !empty($skuOne)&&$skuOne['price'] ? $skuOne['price'] : 0;
//                        $arys['all_income'] += $price * $vv['num'] * $rate;
//                    }
//                }
//            }
//        }
//        //未结算的
//        $orderNos = $this->dbConn($this->dbOrder)
//            ->where('del', 0)
//            ->whereIn('uid', $subUids)
//            ->get();
//        if (count($orderNos)) {
//            foreach ($orderNos as $v) {
//                $oskuOnes = $this->dbConn($this->dbOsku)->where('order_id', $v->id)->get();
//                if (count($oskuOnes)) {
//                    foreach ($oskuOnes as $vv) {
//                        $vv = (array) $vv;
//                        $skuOne = (array) $this->dbConn($this->dbGsku)
//                            ->where('id', $vv['sku_id'])->first();
//                        $rate = !empty($skuOne)&&$skuOne['commission_rate']<100 ? $skuOne['commission_rate'] / 100 : 1;
//                        $price = !empty($skuOne)&&$skuOne['price'] ? $skuOne['price'] : 0;
//                        $arys['income_freeze'] += $price * $vv['num'] * $rate;
//                    }
//                }
//            }
//        }
        $arys['all_income'] = $this->dbConn($this->dbUserIncome)
            ->where('del', 0)
            ->where('uid', $uid)
            ->sum('amount'); //所有的
        $arys['income_freeze'] = $this->dbConn($this->dbUserIncome)
            ->where('del', 0)
            ->where('uid', $uid)
            ->where('status', 1)
            ->sum('amount'); //待结算的
        $arys['settle_income'] = $this->dbConn($this->dbTixian)
            ->where('del', 0)
            ->where('uid', $uid)
            ->where('status', 1)
            ->sum('amount'); //审核中的
        $arys['income'] = $this->dbConn($this->dbTixian)
            ->where('del', 0)
            ->where('uid', $uid)
            ->where('status', 2)
            ->sum('amount'); //已提现的
        $arys['tixian'] = $arys['all_income'] - $arys['income_freeze']
            - $arys['settle_income'] - $arys['income']; //可提现的
        $this->dbConn($this->dbUser)->where('id', $uid)->update([
            'all_income' => $arys['all_income'], 'income' => $arys['income'],
            'settle_income' => $arys['settle_income'], 'income_freeze' => $arys['income_freeze'],
        ]);
        return $arys;
    }
}